package com.CMUBiS.PageServlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.CMUBiS.Data.Error;
import com.CMUBiS.Data.Footer;
import com.CMUBiS.Data.GlobalVars;
import com.CMUBiS.Data.Header;
import com.CMUBiS.PageControllers.BrowseCategoryController;
import com.CMUBiS.util.Image;
import com.CMUBiS.util.Item;
import com.CMUBiS.util.StopWatch;

/**
 * This page allows the user to browse items
 * 
 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
 * @version 0.1
 * @since 0.1
 * @date 04/05/2011
 */

@WebServlet(name="BrowseCategoryServlet", urlPatterns="/browsecategory")
public class BrowseCategoryServlet extends HttpServlet{
	private static final long serialVersionUID = 6472741003023438743L;
	private static final String EMPTY = "";
	private static final String title = "Browse Category";
	
	/**
	 * Get the page, calls the page to be made
	 * We used to check the parameters in here, but I moved it to a controller object to keep the logic away from the layout
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(GlobalVars.isHTML4){
			makePage(request, response, Boolean.FALSE);
		}else{
			

			PrintWriter out = response.getWriter();
			response.setContentType("application/json");
			try {
				ArrayList<Item> items=GlobalVars.db.getCategoryItems(Integer.parseInt(request.getParameter("categoryID")), Integer.parseInt(request.getParameter("pageNo")),Integer.parseInt(request.getParameter("itemsPP")));
				if(items.size()>0){
					String output="["+items.get(0).toJSON();
						for(int i=1; i < items.size(); i++){
							output=output+","+items.get(i).toJSON();
						}
						output=output+"]";
						out.println(output);
				}else{
					out.println("[]");
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
			
		}
	}
	
	/**
	 * Get the page, we can just pass this to doPost since the client generator will be posting userIDs and authTokens all the time
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		if(GlobalVars.isHTML4){
			makePage(request, response, Boolean.TRUE);
		}else{
		
			PrintWriter out = response.getWriter();
			response.setContentType("application/json");
			try {
				ArrayList<Item> items=GlobalVars.db.getCategoryItems(Integer.parseInt(request.getParameter("categoryID")), Integer.parseInt(request.getParameter("pageNo")),Integer.parseInt(request.getParameter("itemsPP")));
				if(items.size()>0){
					String output="["+items.get(0).toJSON();
						for(int i=1; i < items.size(); i++){
							output=output+","+items.get(i).toJSON();
						}
						output=output+"]";
						out.println(output);
				}else{
					out.println("[]");
				}
			}catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	/**
	 * This method starts the page timer, writes the header, creates the HTML for the page, writes the stats, and the footer
	 * 
	 * @param request
	 * @param response
	 * @param errorString
	 * @throws ServletException
	 * @throws IOException
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void makePage(HttpServletRequest request, HttpServletResponse response, Boolean isGet)  throws ServletException, IOException {
		if(request !=null && response != null){
			// Do the timer if we are collecting stats
			StopWatch timer;
			if(GlobalVars.collectStats){
				timer = new StopWatch();
				timer.start();
			}
			
			// Create a new page controller for this page, it will get and process the data
			BrowseCategoryController vars = new BrowseCategoryController();
			vars.checkInputs(request);
			
			// We are using PrintWriter to be friendly to the international community. PrintWrite auto-converts coding
			PrintWriter out = response.getWriter();
	
			// Set the return type
			response.setContentType("text/html");
			
			// Write the page header
			Header.writeHeader(out, title, vars.getUserIDString(), vars.getAuthTokenString());
			
			// If the output is to be suppressed then we'll redirect the output
			if(vars.getSuppressOutput())
				out = new PrintWriter(GlobalVars.blackHole);
			
			// Do HTML4 or 5 depending on the global variables
			if(GlobalVars.isHTML4)
				createHTML4(out, vars, isGet);
			else
				createHTML5(out, vars, isGet);
			
			// Redirect the output to start writing the the user again in case we were putting it in the black hole
			out = response.getWriter();
			
			/*
			 * Output any errors. These don't need to be too pretty since we hope there isn't any!
			 * We put them here to help with debug and info, the page above should show pretty ones for users
			 */
			if(GlobalVars.printAllErrors){
				out.println("<BR />Errors: " + vars.getErrors().size());
				for(Error error: vars.getErrors())
					out.println("<BR />" + error.getErrorNumber() + " " +error.toString());
			}
			
			/*
			 * Process the page time
			 */
			if(GlobalVars.collectStats){
				timer.stop();
				vars.setTotalTime(timer.getTimeTaken());
				GlobalVars.addStats(request, out, vars);
			}
			
			// Write the page footer
			Footer.writeFooter(out);
		}
	}
	
	/**
	 * Creates the HTML4 version of the website
	 * 
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML4(PrintWriter out, BrowseCategoryController vars, Boolean isGet){
		if(out != null && vars != null)
		try{		
			// Get the data needed to display the page
			vars.getHTML4Data();
			vars.processHTML4();
			
			/*
			 * Print all of the current category and sub-categories
			 */
			out.println("<div id=\"left\">");
			
				// Print out the current category
				String parentCategoryURL = vars.getParentCategoryURL();
				if(parentCategoryURL != null && !parentCategoryURL.equals("null")){
					out.println("<div id=\"center\">");
						out.println(vars.getParentCategoryURL());
					out.println("</div>");
				}
				
				// Print out all of the sub categories
				String[] subCategoryURLs = vars.getSubCategoryURLs();
				
				if(subCategoryURLs != null)
				for(int i=0; i < subCategoryURLs.length; i++){
					out.println("<div id=\"center\">");
						out.println(subCategoryURLs[i]);
					out.println("</div>");
				}
			
			out.println("</div>");
			
			/*
			 * Print out all of the items in the current category	
			 */
			ArrayList<Item> items = vars.getItems();
			String[] itemURLs = vars.getItemURLs();	
			
			out.println("<div id=\"center\">");
			
				out.println("Name");
				out.println("Description");
				out.println("Current Bid");
				out.println("End date");
				
				if(itemURLs != null && itemURLs.length > 0)
				for(int i=0; i < itemURLs.length; i++){
					Item item = items.get(i);
					String thumbnail = item.getThumbnail();
					
					/*
					 * Thumbnail
					 * Link
					 * CurrentBid
					 * End date
					 */
					out.println("<div id=\"entry\">");
					out.println("<img height=\"60\" width=\"60\" scr=\"" + thumbnail + "\" alt=\"" + item.getDescription() + "\">");
					out.print("<label for=\"itemlink"); out.print(i); out.print("\">"); out.print(itemURLs[i]); out.println("</label>");
					out.println(item.getCurrentBid());
					out.println(item.getEndDate());
					out.println("</div>");
				}
				else
					out.println("<BR /> Sorry, there are not items to view");
			
			out.println("</div>");
			
			/*
			 * Print the previous page and next page links
			 */
			out.print(vars.getPreviousPageURL());
			out.print(" | ");
			out.print(vars.getNextPageURL());
		}
		catch(Exception e){
			//TODO: make this output to a file
			e.printStackTrace();
		}
	}
	
	/**
	 * Creates the HTML5 version of the website
	 * 
	 * @param request The incoming request
	 * @param response The response sent to the user
	 * @param out The out writer to write the HTML to
	 * @return The HTML5 response (although it could just return void since it writes to the requests out writer)
	 * @author Andy (andrewtu@cmu.edu, turner.andy@gmail.com)
	 */
	public void createHTML5(PrintWriter out, BrowseCategoryController vars, Boolean isGet){
		if(out != null && vars != null)
		try{
			// Get the data needed to display the page
			vars.getHTML5Data();
			vars.processHTML5();
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
}
